package com.cqeec.demo.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.TimeZone;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * FTP上传下载工具类
 * 
 * @Title: FtpUtil
 * @Descripton: 用于FTP上传下载
 */
public class FtpUtil {
	
	private FTPClient ftpClient;
    private String strIp;
    private int intPort;
    private String user;
    private String password;

    /**
     * 构造函数
     * @param strIp		FTP服务器IP地址
     * @param intPort	端口号
     * @param user		登录的用户名
     * @param Password	登录密码
     */
    public FtpUtil(String strIp, int intPort, String user, String Password) {
        this.strIp = strIp;
        this.intPort = intPort;
        this.user = user;
        this.password = Password;
        this.ftpClient = new FTPClient();
    }
    
    /**
     * 判断是否登入成功 
     * @return
     */
    public boolean ftpLogin() {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftpClient.setControlEncoding("UTF-8");
        this.ftpClient.configure(ftpClientConfig);
        try {
            if (this.intPort > 0) {
                this.ftpClient.connect(this.strIp, this.intPort);
            } else {
                this.ftpClient.connect(this.strIp);
            }
            // FTP服务器连接回答  
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
            	//登录FTP服务失败！
                this.ftpClient.disconnect();
                return isLogin;
            }
            this.ftpClient.login(this.user, this.password);
            // 设置传输协议  
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //登陆FTP服务器成功
            isLogin = true;
        } catch (Exception e) {
        	//登录FTP服务失败！
            e.printStackTrace();
        }
        this.ftpClient.setBufferSize(1024 * 2);
        this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }
  
    /**
     * 退出关闭服务器链接 
     */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
            	// 退出FTP服务器
                boolean reuslt = this.ftpClient.logout();
                if (reuslt) {
                	//成功退出服务器
                }
            } catch (IOException e) {
            	//退出FTP服务器异常！
                e.printStackTrace();
            } finally {
                try {
                	// 关闭FTP服务器的连接  
                    this.ftpClient.disconnect();
                } catch (IOException e) {
                	//关闭FTP服务器的连接异常！
                    e.printStackTrace();
                }
            }
        }
    }
  
    /**
     * 上传Ftp文件
     * @param localFile			本地文件
     * @param romotUpLoadePath	上传服务器路径-应该以/结束
     * @return
     */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
        	//改变工作路径
            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            //开始上传
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            if (success == true) {
            	//上传成功
                return success;
            }
        } catch (FileNotFoundException e) {
        	//未找到
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
    
    /**
     * 上传Ftp文件
     * @param inStream			文件输入流
     * @param fileName			文件名称
     * @param romotUpLoadePath	上传服务器路径-应该以/结束
     * @return
     */
    public boolean uploadFile(InputStream inStream,String fileName,String romotUpLoadePath) {
        boolean success = false;
        try {
        	//改变工作路径
            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);
            success = this.ftpClient.storeFile(fileName, inStream);
            if (success == true) {
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
    
    /**
     * 下载文件
     * @param remoteFileName		待下载文件名称
     * @param localDires			下载到本地那个路径下
     * @param remoteDownLoadPath	remoteFileName所在的路径
     * @return
     */
    public boolean downloadFile(String remoteFileName, String localDires,String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new BufferedOutputStream(new FileOutputStream(strFilePath));
            //开始下载
            success = this.ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true) {
            	//成功下载到strFilePath
                return success;
            }
        } catch (Exception e) {
        	//下载失败
            e.printStackTrace();
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
        	//下载失败!!!
        }
        return success;
    }
    
    /**
     * 上传文件夹
     * @param localDirectory		本地文件夹
     * @param remoteDirectoryPath	Ftp服务器路径-以目录"/"结束
     * @return
     */
    public boolean uploadDirectory(String localDirectory,String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            this.ftpClient.makeDirectory(remoteDirectoryPath);
            //ftpClient.listDirectories();
        } catch (IOException e) {
        	//目录创建失败
            e.printStackTrace();
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                uploadFile(new File(srcName), remoteDirectoryPath);
            }
        }
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                //递归  
                uploadDirectory(allFile[currentFile].getPath().toString(),remoteDirectoryPath);
            }
        }
        return true;
    }
  
    /**
     * 下载文件夹
     * @param localDirectoryPath	本地地址
     * @param remoteDirectory		远程文件夹
     **/
    public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
        try {
            String fileName = new File(remoteDirectory).getName();
            localDirectoryPath = localDirectoryPath + fileName + "//";
            new File(localDirectoryPath).mkdirs();
            FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
                    downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
                }
            }
        } catch (IOException e) {
        	//下载文件夹失败
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    //FtpClient的Set和 Get函数
    public FTPClient getFtpClient() {
        return ftpClient;
    }
    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }
}